package com.zuosh.web;

import com.alibaba.fastjson.JSON;
import com.zuosh.common.ResponseHelper;
import com.zuosh.common.RestResponseCode;
import com.zuosh.common.Result;
import com.zuosh.domain.UserPost;
import com.zuosh.domain.UserPostExample;
import com.zuosh.service.PostService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.ImportResource;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by zuoshuai on 2017/3/17.
 */
@RestController
@RequestMapping(value = "api/post")
public class PostController {
    Logger LOGGER = LoggerFactory.getLogger(this.getClass());//logger
    @Resource
    private PostService postService;

    @PostMapping(value = "/add_post")
    public ResponseHelper.RestResponse<Object> addPost(HttpServletRequest request, @RequestBody UserPost userPost) {
        if (userPost == null) {
            return ResponseHelper.buildResponse(RestResponseCode._400, null, "参数不可为空");
        }
        LOGGER.debug("[addPost]收到 添加帖子 请求 ,参数: {}", JSON.toJSONString(userPost));
        Result<Long> activeUserResult = postService.addPost(userPost);
        if (activeUserResult.isSuccess()) {
            return ResponseHelper.buildResponse(RestResponseCode._200, activeUserResult.getData(), activeUserResult.getMsg());
        } else {
            return ResponseHelper.buildResponse(RestResponseCode._500, activeUserResult.getData(), activeUserResult.getMsg());
        }
    }

    @GetMapping(value = "/list_posts")
    public ResponseHelper.RestResponse<Object> listPosts(HttpServletRequest request, Long userId) {
        if (userId == null) {
            return ResponseHelper.buildResponse(RestResponseCode._400, null, "参数不可为空");
        }
        LOGGER.debug("[listPosts]收到 帖子列表 请求 ,参数: {}", userId);
        UserPostExample postExample = new UserPostExample();
        postExample.createCriteria().andUserIdEqualTo(userId);
        Result<List<UserPost>> activeUserResult = postService.listPosts(postExample);
        if (activeUserResult.isSuccess()) {
            return ResponseHelper.buildResponse(RestResponseCode._200, activeUserResult.getData(), activeUserResult.getMsg());
        } else {
            return ResponseHelper.buildResponse(RestResponseCode._500, activeUserResult.getData(), activeUserResult.getMsg());
        }
    }

}
